﻿# -*- coding: UTF-8 -*-
import logging
import requests
import asyncio
from requests.auth import HTTPBasicAuth
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from datetime import datetime


# log_file_path = "/data/python/log/rabbitmq.log"
log_file_path = "./rabbitmq.log"
logging.basicConfig(
    filename=log_file_path,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)


def nowTime():
    now = datetime.now()
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_time


def create_client() -> Dysmsapi20170525Client:
    config = open_api_models.Config(
        access_key_id="LTAI4GHoGkVBr1CT5C57Y64j",
        access_key_secret="5apl1h6CDXS2IBdmpKIhaHXhgIAxJv",
    )
    config.endpoint = f"dysmsapi.aliyuncs.com"
    return Dysmsapi20170525Client(config)


async def Send_message(key):
    client = create_client()
    send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
        phone_numbers="13421830635",  # 接收短信的手机号码
        sign_name="爱问健康",  # 短信签名名称
        template_code="SMS_466375121",  # 短信模板代码
        template_param='{"key":"%s"}' % (key),  # 短信模板参数
    )

    runtime = util_models.RuntimeOptions()

    try:
        await client.send_sms_with_options_async(send_sms_request, runtime)
    except Exception as error:
        err_msg = error.message
        logging.error(f"发送信息出错：{err_msg}\n")
        err_addr = error.data.get("Recommend")
        logging.error(f"诊断地址：{err_addr}\n")


async def Get_MQ_Deliver():
    url = "http://10.5.1.48:15672/api/queues"
    username = "cloud"
    password = "7#BD2CFc3TBV}7m7z"
    tasks = []  # 用于存储发送告警信息的任务
    response = requests.get(url, auth=HTTPBasicAuth(username, password))

    if response.status_code == 200:
        queues = response.json()
        total_deliver_manual_ack_rate = 0

        for queue in queues:
            message_stats = queue.get("message_stats", {})
            deliver_auto_ack_rate = message_stats.get("deliver_no_ack_details", {}).get(
                "rate", 0
            )
            deliver_rate = message_stats.get("deliver_details", {}).get("rate", 0)
            deliver_manual_ack_rate = deliver_rate - deliver_auto_ack_rate
            total_deliver_manual_ack_rate += deliver_manual_ack_rate

        total_deliver_manual_ack_rate = round(total_deliver_manual_ack_rate, 1)

        print(f"Deliver (manual ack): {total_deliver_manual_ack_rate}/s")
        logging.info(f"Deliver (manual ack): {total_deliver_manual_ack_rate}/s")
        key = "Deliver (manual ack): {}/s".format(total_deliver_manual_ack_rate)
        print(key)
        # 创建一个协程来发送告警信息
        send_message_task = asyncio.ensure_future(Send_message(key))

        # 等待5秒后继续下一个任务
        await asyncio.sleep(10)

        # 将任务添加到列表中
        tasks.append(send_message_task)

    else:
        print(f"数据获取错误: {response.status_code}")

    # 等待所有任务完成
    await asyncio.gather(*tasks)
    logging.info("所有告警信息已发送！")


# 主函数
async def Run_spiders_and_compare():
    await Get_MQ_Deliver()
    logging.info("程序运行结束。\n")


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(Get_MQ_Deliver())
    finally:
        loop.close()
